﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Markup;
using System.Collections.Specialized;
using System.Windows.Data;

namespace TouchControls
{
    [ContentPropertyAttribute("Items")]
    public partial class TouchPivot : ItemsControl
    {
        private Panel _headers;
        private TranslateTransform _headersTranslate;
        private Panel _items;
        private TranslateTransform _itemsTranslate;
        private Panel _headersContainer;
        private Panel _itemsWrap;
        private Panel _root;
        private PivotHeader _ghostHeader;

        public TouchPivot()
        {
            // apply default style
            this.DefaultStyleKey = typeof(TouchPivot);

            this.Loaded += new RoutedEventHandler(TouchPivot_Loaded);
        }

        void TouchPivot_Loaded(object sender, RoutedEventArgs e)
        {
            _itemsPositionDirty = true;
            this.PositionItems();
        }              

        public override void OnApplyTemplate()
        {             
            base.OnApplyTemplate();
            _root = (Panel)this.GetTemplateChild("LayoutRoot");
            _headersContainer = (Panel)this.GetTemplateChild("HeadersContainer");
            _headers = (Panel)this.GetTemplateChild("HeadersPanelHost");
            _headersTranslate = (TranslateTransform)this.GetTemplateChild("HeadersTranslate");
            _itemsWrap = (Panel)this.GetTemplateChild("ItemsWrapper");
            _items = (Panel)this.GetTemplateChild("ItemsPanelHost");
            _itemsTranslate = (TranslateTransform)this.GetTemplateChild("ItemsTranslate");
            this.RegisterName("ITEMSTRANSLATE", _itemsTranslate);
            this.RegisterName("HEADERSTRANSLATE", _headersTranslate);

            //AddHandler(TouchPivot.ManipulationStartedEvent, new EventHandler<ManipulationStartedEventArgs>(this.ManipulationStarted), true);
            //AddHandler(TouchPivot.ManipulationDeltaEvent, new EventHandler<ManipulationDeltaEventArgs>(this.ManipulationDelta));
            //AddHandler(TouchPivot.ManipulationCompletedEvent, new EventHandler<ManipulationCompletedEventArgs>(this.ManipulationCompleted));
            IsManipulationEnabled = true;
                        
            _ghostHeader = new PivotHeader();
            _headers.Children.Add(_ghostHeader);
            _ghostHeader.StateUnselected();

            foreach (PivotItem item in Items)
            {
                var title = new PivotHeader();                
                title.Item = item;
                item.Header = title;
                Binding bd = new Binding("Title");
                bd.Source = item;
                title.SetBinding(PivotHeader.ContentProperty, bd);                
                _headers.Children.Add(title);
            }
            _itemsPositionDirty = true;
            //PositionItems();
        }

        private bool _itemsPositionDirty = false;

        private int _firstMenuMargin = 0;

        private void PositionItems()
        {
            if (ActualWidth == 0 || !_itemsPositionDirty) 
                return;

            _itemsTranslate.X = 0;
            _headersTranslate.X = 0;
            
            _itemsPositionDirty = false;
            double headerOffset = _firstMenuMargin;
            var selectedItem = (PivotItem)Items[SelectedIndex];
            selectedItem.Header.StateSelected();
            PositionItem(selectedItem, 0, 0);
            
            int cursor = SelectedIndex;
            int itemcount = 0;
            while (itemcount < Items.Count)
            //for (int i = 0; i < Items.Count; i++ )
            {
                if (cursor >= Items.Count) cursor = 0;

                var item = (PivotItem)Items[cursor];

                if (cursor != SelectedIndex)
                {
                    item.Header.StateUnselected(); 
                    PositionItem(item, -2000, -2000);
                    
                    item.ItemContent.Visibility = Visibility.Collapsed;
                }
                PositionItem(item.Header, headerOffset, 0);
                headerOffset += item.Header.RenderSize.Width;
                itemcount++;
                cursor++;
            }

            var nextItem = this.GetNextItem();
            var prevItem = this.GetPrevItem();

            selectedItem.ItemContent.Visibility = Visibility.Visible;

            if (nextItem != selectedItem)
            {
                PositionItem(nextItem, ActualWidth, 0);                
            }

            _ghostHeader.Content = prevItem.Header.Content;
            _ghostHeader.StateUnselected();
            PositionItem(_ghostHeader, _firstMenuMargin - prevItem.Header.ActualWidth, 0);
            /*
            if (nextItem == prevItem) //In this case we have just 2 items and we must allow to scroll in both directions
            {
                _ghostHeader.Content = nextItem.Header.Content;
                PositionItem(_ghostHeader, _firstMenuMargin - nextItem.Header.ActualWidth, 0);
            }
            else
            {
                PositionItem(prevItem, -ActualWidth, 0);
                //PositionItem(prevItem.Header, -prevItem.Header.ActualWidth, 0); 
            }
             */
        }

        private PivotItem GetPrevItem()
        {
            var prevItemIndex = SelectedIndex - 1;
            if (prevItemIndex < 0)
            {
                prevItemIndex = Items.Count - 1;
            }
            return (PivotItem)Items[prevItemIndex];
        }

        private PivotItem GetNextItem()
        {
            var nextItemIndex = SelectedIndex + 1;
            if (nextItemIndex >= Items.Count)
            {
                nextItemIndex = 0;
            }
            return (PivotItem)Items[nextItemIndex];
        }

        private static void PositionItem(UIElement item, double X, double Y)
        {
            Canvas.SetLeft(item, X);            
            Canvas.SetTop(item, Y);
        }

        protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
        {
            base.OnRenderSizeChanged(sizeInfo);
            foreach (PivotItem item in Items)
            {
                item.Width = _itemsWrap.ActualWidth;
                item.Height = _itemsWrap.ActualHeight;
            }
            _itemsPositionDirty = true;
            this.PositionItems();
        }        
        
        /*protected override Size ArrangeOverride(Size arrangeBounds)
        {
            var res = base.ArrangeOverride(arrangeBounds);
            foreach (PivotItem item in Items)
            {
                item.Width = _itemsWrap.ActualWidth;
                item.Height = _itemsWrap.ActualHeight;
            }
            _itemsPositionDirty = true;
            this.PositionItems();
            return res;
        }*/
    }
}
